<script setup>
import { reactive, ref } from 'vue'
import { RouterLink, useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const userStore = useUserStore()
const ruleFormRef = ref()

const validatePass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入用户名'))
  } else {
    if (ruleForm.password !== '') {
      if (!ruleFormRef.value) return
      ruleFormRef.value.validateField('password')
    }
    callback()
  }
}
const validatePass2 = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('密码不能为空'))
  } else callback()
}

const ruleForm = reactive({
  username: '',
  password: ''
})

const rules = reactive({
  username: [{ validator: validatePass, trigger: 'blur' }],
  password: [{ validator: validatePass2, trigger: 'blur' }]
})

const submitForm = async (formEl) => {
  if (!formEl) return
  await formEl.validate()
  if (userStore.login(ruleForm.username, ruleForm.password))
    router.push('/admin')
}
</script>

<template>
  <div class="form">
    <div class="logo">
      <img src="@/assets/img/logo.png" width="200" alt="" />
      <h1 align="center">登陆</h1>
    </div>
    <div class="form-container">
      <el-form
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="ruleForm"
        status-icon
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名:" prop="username">
          <el-input
            v-model="ruleForm.username"
            type="text"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item label="密码:" prop="password">
          <el-input
            v-model="ruleForm.password"
            type="password"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item>
          <router-link to="/register">没有账号？去注册</router-link>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            class="login-btn"
            @click="submitForm(ruleFormRef)"
          >
            登录
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<style scoped>
h1 {
  font-size: 30px;
  color: white;
  letter-spacing: 10px;
}

.login-btn {
  display: block;
  width: 100%;
  color: white;
}

.form {
  height: 100vh;
  width: 100vw;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  background-image: linear-gradient(45deg, #763473, #413976, #25236e);
}

.el-form-item {
  width: 400px;
  margin: 30px 0;
}

.form-container {
  background-color: rgba(255, 255, 255, 0.705);
  padding: 50px;
  border-radius: 50px;
  border: 1px solid gray;
}
</style>
